package com.atguigu.juc.atomics;

import java.net.SocketTimeoutException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yanglin
 * @create 2024-01-25 17:12 星期四
 * description:
 */
public class AtomicIntegerDemo {
    
    public static int SIZE = 50;

    public static void main(String[] args) throws InterruptedException {
        Number number = new Number();
        CountDownLatch countDownLatch = new CountDownLatch(SIZE);
        for (int i = 0; i < SIZE; i++) {
            new Thread(() -> {
                try {
                    for (int j = 0; j < 1000; j++) {
                        number.addPlusPlus();            
                    }
                } finally {
                    countDownLatch.countDown();
                }
            }).start();
        }
        
        //等待50个线程全部计算完成之后，在去获得最终值
        countDownLatch.await();

        System.out.println(Thread.currentThread().getName() + "\t result = " + number.atomicInteger.get());
    }
    
    
}

class Number {
    AtomicInteger atomicInteger = new AtomicInteger();
    
    public void addPlusPlus(){
        atomicInteger.getAndIncrement();
    }
}